package cate.game.pvp.gradepvp;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

public class GradePvpHelper {
    /** 整个赛季持续时间 */
    private static final long WHOLE_SEASON_TIME = 28 * 24 * 3600 * 1000L;

    // 计算当前是第几赛季
    public static int calcCurrentSeason(long startTime) {
        return calcCurrentSeason(startTime, System.currentTimeMillis());
    }

    // 计算当前是第几赛季
    public static int calcCurrentSeason(long startTime, long timestamp) {
        if (startTime == 0 || timestamp < startTime) {
            return 0;
        }
        long between = timestamp - startTime;
        return (int) (between / WHOLE_SEASON_TIME) + 1;
    }

    // 当前赛季的开启时间
    public static long calcCurSeasonStartTime(long startTime) {
        long now = System.currentTimeMillis();
        if (now < startTime) {
            return startTime;
        }
        long between = now - startTime;
        return now - between % WHOLE_SEASON_TIME;
    }

    // 当前赛季的开启时间
    public static long calcCurSeasonStartTime(long startTime, long timestamp) {
        if (timestamp < startTime) {
            return startTime;
        }
        long between = timestamp - startTime;
        return timestamp - between % WHOLE_SEASON_TIME;
    }

    // 当前是否上半赛季
    public static boolean isFirstHalfSeason(long startTime) {
        long now = System.currentTimeMillis();
        if (now < startTime) {
            return true;
        }
        long between = now - startTime;
        return between % WHOLE_SEASON_TIME <= GradePvpPeriod.FIRST_HALF.getEndTime();
    }

    // 当前赛季已经持续了多少时间
    public static long currentSeasonContinueTime(long startTime) {
        return System.currentTimeMillis() - calcCurSeasonStartTime(startTime);
    }

    public static GradePvpPeriod currentSeasonPeriod(long startTime) {
        long now = System.currentTimeMillis();
        if (now < startTime) {
            return GradePvpPeriod.NOT_OPEN;
        }
        long continueTime = currentSeasonContinueTime(startTime);
        if(continueTime == 0L){
            continueTime = 1L;
        }
        return GradePvpPeriod.getCurrentStatus(continueTime);
    }

    public static long dateStrToMillis(String dateStr) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime parse = LocalDateTime.parse(dateStr, df);
        return LocalDateTime.from(parse).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
    }

    public static boolean isOpen() {
        return LocalDateTime.now().getHour() < 23;
    }
}
